package com.fzl.spring_chatroom.service;

import com.fzl.spring_chatroom.common.exception.UseException;
import com.fzl.spring_chatroom.model.dao.User;
import com.fzl.spring_chatroom.model.mapper.UserMapper;
import com.fzl.spring_chatroom.model.request.UserLoginRequest;
import com.fzl.spring_chatroom.model.request.UserRegisRequest;
import com.fzl.spring_chatroom.model.response.UserInfoResponse;
import com.fzl.spring_chatroom.model.response.UserLoginResponse;
import com.fzl.spring_chatroom.utils.JwtUtils;
import com.fzl.spring_chatroom.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    // public Boolean insert(UserRegisRequest userRegisRequest) {
    // return userMapper.insertUser(userRegisRequest);
    // }

    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        User user = userMapper.selectUserByName(userLoginRequest.getUsername());
        if (user == null) {
            throw new UseException("请填写正确的用户名");
        }
        if (!SecurityUtil.verify(userLoginRequest.getPassword(), user.getPassword())) {
            throw new UseException("用户密码错误");
        }
        // 密码正确
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getUserId());
        map.put("name", user.getUsername());
        String token = JwtUtils.genToken(map);
        return new UserLoginResponse(user.getUserId(), user.getUsername(), token);
    }

    public Boolean register(UserRegisRequest userRegisRequest) {
        User user = new User();
        BeanUtils.copyProperties(userRegisRequest, user);
        try {
            user.setPassword(SecurityUtil.encrypt(userRegisRequest.getPassword()));
            Integer result = userMapper.insert(user);
            if (result == 1) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("用户注册失败：" + e);
            throw new UseException("用户注册失败，内部错误，请联系管理员");
        }
    }

    public UserInfoResponse getUser(Integer userId) {
        User user = userMapper.selectUserById(userId);
        String avatar = (user.getAvatar() == null || user.getAvatar().isEmpty()) ? "/avatar/default.png"
                : user.getAvatar();
        return new UserInfoResponse(user.getUserId(), user.getUsername(), avatar);
    }

    public void updateAvatar(Integer userId, String avatar) {
        userMapper.updateAvatar(userId, avatar);
    }

    public User searchUser(String keyword) {
        return userMapper.selectUserByIdOrName(keyword);
    }
}
